<script setup lang="ts">
import { type ColProps, TableColumn } from "@arco-design/web-vue";
import { onMounted, reactive, ref, computed, h } from "vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import { getReviewList, getDetail } from "@/services/reviewStatistics";
import type { ExpertGroupListType } from "@/types/expertGroup";
import {
  getDictByParentCode,
  getDictByParentCodeOut,
  listNormalRacetrack,
  listNormalRacetrackOut,
  listRacetrack,
  listRacetrackOut,
} from "@/services/commonApi.ts";
import Local from "@/utils/local";
import { getUser } from "@/utils";
import AchieveModal from "@/pages/review/achievement/AchieveModal.vue";
import type { achievementType } from "@/types/achievement.ts";
import {standardList, standardListOut} from "@/services/scoreApi.ts";
// standardList
const colProps: ColProps = {
  xs: 24,
  sm: 24,
  md: 12,
  lg: 4,
  xl: 4,
  xxl: 4,
  span: 4,
};

const colProps2: ColProps = {
  xs: 24,
  sm: 24,
  md: 12,
  lg: 4,
  xl: 4,
  xxl: 4,
  span: 4,
};

const loading = reactive({
  search: false, // 查询按钮的 Loading
  reset: false, // 重置按钮的 Loading
  import: false, // 导入按钮的 Loading
  export: false, // 导出按钮的 Loading
  downloadTemplate: false, // 裁判模板下载按钮的 Loading
  print: false, // 打印按钮的 Loading
  batchDelete: false, // 批量删除的 Loading
  deleteAll: false, // 全部删除的 Loading
  table: false,
  edit: false,
  delete: false,
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
});

const achieveRef = ref<{
  init: (data: achievementType) => void;
}>();

const visible = ref(false);
const drawer = ref<{
  showDialog: () => {};
  hideDialog: () => {};
}>();


const data = ref<ExpertGroupListType>([]);

const searchValue = reactive({
  phone: "",
  projectType: "",
  channel: "",
  projectSource: "",
  teacherId: JSON.parse(Local.localRead("teacher")).teacherId,
});

const form = ref([]);

const options = reactive<{
  赛道: [];
  参赛项目来源: [];
}>({
  赛道: [],
  参赛项目来源: [],
});

const columns: TableColumn[] = [
  {
    title: "序号",
    dataIndex: "index",
    width: 80,
    slotName: "index",
    align: "center",
  },
  {
    title: "报名用户电话",
    key: "phone",
    dataIndex: "phone",
    align: "center",
  },
  {
    title: "项目名称",
    key: "projectName",
    dataIndex: "projectName",
    align: "left",
  },
  {
    title: "赛道类型",
    key: "projectType",
    dataIndex: "projectType",
    align: "center",
    slotName: "projectType",
  },
  {
    title: "赛道",
    key: "channel",
    dataIndex: "channel",
    align: "center",
  },
  {
    title: "参赛项目来源",
    key: "projectSource",
    dataIndex: "projectSource",
    align: "center",
  },
  {
    title: "总分",
    key: "finalScore",
    dataIndex: "finalScore",
    align: "center",
  },
  {
    title: "操作",
    slotName: "operate",
    align: "center",
    width: 160,
    fixed: "right",
  },
];

const moduleId = () => {
  return Local.localRead("moduleId") || ""
}

// 查询
const handleSearch = () => {
  pagination.current = 1;
  getList();
};
// 重置
const handleReset = () => {
  searchValue.phone = "";
  searchValue.projectType = "";
  searchValue.channel = "";
  searchValue.projectSource = "";
  options["赛道"] = [];
  handleSearch();
};

// 分页
const handlePageChange = (page: number) => {
  pagination.current = page;
  getList();
};

const getList = () => {
  getReviewList({
    current: pagination.current,
    size: pagination.pageSize,
    phone: searchValue.phone,
    projectType: searchValue.projectType,
    channel: searchValue.channel,
    projectSource: searchValue.projectSource,
    teacherId: searchValue.teacherId,
  }).then((res) => {
    data.value = res.data.records;
    pagination.total = res.data.total;
    pagination.current = res.data.current;
    pagination.pageSize = res.data.size;
  });
};


const handleDetail = (record) => {
  console.log(123)
  // console.log(record)
  // moduleId
  // moduleId: moduleId(),
  standardListOut({moduleId: moduleId()}).then(res => {
    getDetail({
      registUid: record.registUid, //报名用户id
      teacherId: JSON.parse(Local.localRead("teacher")).teacherId, //专家id
    }).then((key) => {
      const list = key.data[0].recordList
      form.value = res.data.map(item => {
        const find = list.find(f => f.standardId === item.id)
        if (find) {
          console.log(find)
        }
        return {
          ...item,
          score: find ? find.score : 0,
          markTime: find ? find.markTime : 0,
        }
      })
    });

  }).finally(() => {
    visible.value = true
  })

};

const handleAchieve = (row: achievementType) => {
  achieveRef.value?.init(row);
};


function formatLevel1TextWithBoldIntro(text: string) {
  // 判断是否以编号开头（如 1.、2.）
  // const startsWithNumber = /^\d+\./.test(text);

  const startsWithNumber = /^[1-9]\d*\./.test(text);

  if (startsWithNumber) {
    // 如果以编号开头，只换行，不加粗
    return text.replace(/(\d+\..*?)(?=\d+\.|$)/gs, "<br>$1").trim();
  }

  // 否则，加粗开头部分，换行编号部分
  const regex = /^([^\d]+?)(?=\d+\.)/s;
  const match = text.match(regex);

  if (match) {
    const [, intro] = match;
    const numberedContent = text.substring(intro.length).trim();
    const formattedNumberedContent = numberedContent.replace(
      /(\d+\..*?)(?=\d+\.|$)/gs,
      "<br>$1"
    );
    return `<strong style="font-size: 15px;">${intro.trim()}</strong>${formattedNumberedContent}`;
  }

  if (text.includes("0.5分")) {
    console.log(111);
    return text;
  }

  // 如果没有编号，只加粗并换行
  return `<strong>${text}</strong><br>`;
}



const getColor = (projectType: string) => {
  switch (projectType) {
    case "1":
      return "#168cff";
    case "0":
      return "#00b42a";
  }
};

const getName = (projectType: string) => {
  switch (projectType) {
    case "1":
      return "企业";
    case "0":
      return "常规";
  }
};

onMounted(() => {
  getList();
  optionsList();
});


const handleCancel = () => {
  drawer.value?.hideDialog();
  visible.value = false;
};

const handleClose = () => {
  visible.value = false;
};


const optionsList = () => {
  getDictByParentCodeOut({
    dictCode: "参赛项目来源",
  }).then((res) => {
    if (res.code === 200) {
      options["参赛项目来源"] = res.data[0].children;
      const find = options["参赛项目来源"].find(
        (item) => item.itemText === getUser().username
      );
      if (find) {
        searchValue.projectSource = find.id;
        options["参赛项目来源"] = [find];
      } else {
        searchValue.projectSource = "";
      }
    }
  });
};

const handleSelectChange = (e) => {
  searchValue.channel = "";
  options["赛道"] = [];
  if (e === "0") {
    listNormalRacetrackOut().then((res) => {
      if (res.code === 200) {
        options["赛道"] = res.data;
      }
    });
  } else {
    listRacetrackOut().then((res) => {
      if (res.code === 200) {
        options["赛道"] = res.data;
      }
    });
  }
};

const spanMethodAll = ({ column, rowIndex, record }) => {
  if (column.dataIndex === "name") {
    const prevRecord = rowIndex > 0 ? form.value[rowIndex - 1].name : null;

    if (prevRecord && prevRecord === record.name) {
      return { rowspan: 1, colspan: 1 };
    } else {
      const sameNameCount = form.value.filter(
        (item) => item.name === record.name
      ).length;
      return { rowspan: sameNameCount, colspan: 1 };
    }
  }

  if (column.dataIndex === "level1") {
    const prevRecord = rowIndex > 0 ? form.value[rowIndex - 1] : null;
    if (
      prevRecord &&
      prevRecord.name === record.name &&
      prevRecord.level1 === record.level1
    ) {
      return { rowspan: 0, colspan: 0 };
    } else {
      const sameNameAndLevel1Count = form.value.filter(
        (item) => item.name === record.name && item.level1 === record.level1
      ).length;
      return { rowspan: sameNameAndLevel1Count, colspan: 1 };
    }
  }
  if (column.dataIndex === "score") {
    const prevRecord = rowIndex > 0 ? form.value[rowIndex - 1].name : null;

    if (prevRecord && prevRecord === record.name) {
      return { rowspan: 1, colspan: 1 };
    } else {
      const sameNameCount = form.value.filter(
          (item) => item.name === record.name
      ).length;
      return { rowspan: sameNameCount, colspan: 1 };
    }
  }
  if (column.dataIndex === "markTime") {
    const prevRecord = rowIndex > 0 ? form.value[rowIndex - 1].name : null;

    if (prevRecord && prevRecord === record.name) {
      return { rowspan: 1, colspan: 1 };
    } else {
      const sameNameCount = form.value.filter(
          (item) => item.name === record.name
      ).length;
      return { rowspan: sameNameCount, colspan: 1 };
    }
  }
  return { rowspan: 1, colspan: 1 };
};

const totalScore = computed(() => {
  let sum = 0;
  form.value.forEach((record) => {
    sum += record.score;
  });
  return sum;
});

const columnsForm: TableColumn[] = [
  {
    title: "序号",
    dataIndex: "index",
    width: 80,
    slotName: "index",
  },
  {
    title: "一级指标",
    key: "name",
    dataIndex: "name",
    width: 150,
  },
  {
    title: "分值",
    key: "level1",
    dataIndex: "level1",
    width: 100,
  },
  {
    title: "指标描述",
    key: "level2",
    dataIndex: "level2",
    render: ({ record }) => {
      return h("div", {
        innerHTML: formatLevel1TextWithBoldIntro(record.level2),
      });
    },
  },
  {
    title: "分数",
    key: "score",
    dataIndex: "score",
    width: 80,
  },
  {
    title: "评分时间",
    key: "markTime",
    dataIndex: "markTime",
    width: 200,
  },
];
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form>
        <a-row :gutter="24">
          <a-col v-bind="colProps">
            <a-form-item
              label="报名用户电话"
              label-col-flex="100px"
            >
              <a-input
                allow-clear
                v-model="searchValue.phone"
                placeholder="请输入报名用户电话"
              />
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item
              label="赛道类型"
              label-col-flex="80px"
            >
              <a-select
                v-model="searchValue.projectType"
                placeholder="请选择赛道类型"
                @change="handleSelectChange"
              >
                <a-option value="0">常规赛题</a-option>
                <a-option value="1">企业需求子赛题</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item label="赛道">
              <a-select
                v-model="searchValue.channel"
                placeholder="请选择赛道"
              >
                <a-option
                  v-for="item in options['赛道']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.dictName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item
              label="参赛项目来源"
              label-col-flex="90px"
            >
              <a-select
                v-model="searchValue.projectSource"
                placeholder="请选择参赛项目来源"
              >
                <a-option
                  v-for="item in options['参赛项目来源']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.itemText }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps2">
            <a-form-item :label-col-props="{span: 0}">
              <a-space>
                <a-button
                  type="primary"
                  background-image
                  class="btn"
                  @click="handleSearch"
                  :loading="loading.search"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <span>查询</span>
                </a-button>
                <a-button
                  @click="handleReset"
                  :loading="loading.reset"
                >
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <span>重置</span>
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-table
        :loading="loading.table"
        :data="data"
        :columns="columns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
      >
        <template #index="{rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>

        <template #projectType="{record}">
          <a-tag :color="getColor(record.projectType)">{{ getName(record.projectType) }}</a-tag>
        </template>

        <template #operate="{ record }">
          <a-space>
            <a-button
              type="primary"
              class="btn"
              @click="handleDetail(record)"
              :loading="loading.edit"
            >详情</a-button>
            <a-button
              type="primary"
              class="btn"
              @click="handleAchieve(record)"
            >项目信息</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </a-space>
  <AchieveModal ref="achieveRef" link="out" />
  <a-modal
    width="80%"
    :closable="false"
    @cancel="handleCancel"
    v-model:visible="visible"
    @close="handleCancel"
    ref="drawer"
    title="评分详情"
  >
    <div style="height: 500px;overflow:auto;">
      <h3>总分：{{ totalScore }}</h3>
      <a-table
        :data="form"
        :columns="columnsForm"
        :pagination="false"
        :bordered="tableBorder"
        :span-method="spanMethodAll"
      >
        <template #index="{rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>
        <template #projectType="{record}">
          <a-tag :color="getColor(record.projectType)">{{ getName(record.projectType) }}</a-tag>
        </template>
      </a-table>
    </div>
    <template #footer>
      <a-button @click="handleClose">
        关闭
      </a-button>
    </template>
  </a-modal>
</template>

<style scoped lang="scss">
.btn {
  background-color: #0b0080;
}
</style>